package example.common;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FolderDownload {
    public static ResponseEntity<byte[]> downloadFolder(String fName, String fPath) throws IOException {

        // Creating a temporary zip file
        Path tempFile = Files.createTempFile(fName, ".zip");
        File zipFile = tempFile.toFile();

        // Zipping the folder
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            File sourceFolder = new File(fPath);
            addFolderToZip(sourceFolder, sourceFolder.getName(), zos);
        }

        // Prepare response headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fName + ".zip");

        // Read the file content into a byte array
        byte[] fileContent = Files.readAllBytes(tempFile);

        // Delete the temporary zip file
        zipFile.delete();

        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }

    private static void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                addFolderToZip(file, parentFolder + "/" + file.getName(), zos);
                continue;
            }

            String entryName = parentFolder + "/" + file.getName();
            ZipEntry zipEntry = new ZipEntry(entryName);
            zos.putNextEntry(zipEntry);

            try (InputStream is = new FileInputStream(file)) {
                IOUtils.copy(is, zos);
            }

            zos.closeEntry();
        }
    }
}

